package com.zpark.h5.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.zpark.config.AlipayConfig;
import com.zpark.h5.service.IAlipayH5Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 手机网站支付业务层实现类
 */
@Service
@Slf4j
public class AlipayH5ServiceImpl implements IAlipayH5Service {

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 创建订单
     * @return
     */
    @Override
    public String createOrder() {
        // 1、创建支付宝客户端对象
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppid(),
                alipayConfig.getRsaPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getZhiFuPublicKey(),
                alipayConfig.getSignType()
        );
        // 2、创建支付宝请求对象
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        // 设置同步回调地址
        request.setReturnUrl(alipayConfig.getReturn_url());
        // 设置异步回调地址
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        // 3、创建支付宝请求参数封装对象
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        String orderId = System.currentTimeMillis() + "";
        System.out.println(orderId);
        // 4、设置支付宝请求参数
        // 订单号
        model.setOutTradeNo(orderId);
        // 金额
        model.setTotalAmount("199.9");
        // 订单标题
        model.setSubject("华为蓝牙耳机3.0");
        // 用户取消支付回调
        model.setQuitUrl("https://310dx2074ys0.vicp.fun/h5/quit_pay");

        // 设置交易方式编码
        model.setProductCode("QUICK_WAP_WAY");

        // 将请求参数添加到请求对象当中
        request.setBizModel(model);

        // 5、调用支付宝客户端对象发送请求
        String resultForm = "";
        try {
            // 调用支付宝客户端发起请求
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
            // 6、获取请求结果
            resultForm = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 7、将请求结果响应给客户端
        return resultForm;
    }

    /**
     * 支付成功异步通知
     * @param request
     * @return
     */
    @Override
    public String payNotify(HttpServletRequest request) {
        // 创建map，用于接收存储支付宝POST过来反馈信息
        Map<String, String> map = new HashMap<>();

        // 获取支付宝POST过来反馈信息，获取请求数据map
        Map<String, String[]> requestParams = request.getParameterMap();
        System.out.println("************************    回调参数输出开始    **************************");
        // 遍历请求参数map
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            // 获取参数名
            String name = iter.next();
            // 获取参数值
            String[] values = requestParams.get(name);
            String valueStr = "";

            for (int i = 0; i < values.length; i++) {
                // 拼接成字符串
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }

            // 将参数名，参数值存入map
            map.put(name, valueStr);

            // 输出回调请求参数
            System.out.println(name + "\t\t=\t\t" + valueStr);
        }
        System.out.println("************************    回调参数输出结束    **************************");
        //验证签名
        boolean signVerified = false;
        try {
            // 调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(
                    map,
                    alipayConfig.getZhiFuPublicKey(),
                    alipayConfig.getCharset(),
                    alipayConfig.getSignType());

        } catch (AlipayApiException e) {
            log.info("[支付验证] 异常={}", JSON.toJSONString(e));
            return JSON.toJSONString(e);
        }

        if (signVerified) {
            //处理自己的业务逻辑  将订单支付信息保存到数据库
            log.info("[支付验证] 验证成功={}", JSON.toJSONString(map));
            return JSON.toJSONString(map);
        }

        log.info("[支付验证] 验证结果={}", signVerified);
        return null;
    }

    /**
     * 退款
     * @param orderId 订单id
     */
    @Override
    public void refund(String orderId) {
        // 创建支付宝客户端
        AlipayClient client = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppid(),
                alipayConfig.getRsaPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getZhiFuPublicKey(),
                alipayConfig.getSignType());

        // 创建退款请求对象
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        // 创建退款请求参数封装对象
        AlipayTradeRefundModel model=new AlipayTradeRefundModel();
        //退款的订单Id，也可以设置流水号
        model.setOutTradeNo(orderId);
        //退款金额
        model.setRefundAmount("199.9");

        // 设置请求参数
        alipayRequest.setBizModel(model);
        // 退款结果
        String alipayResponse = "";
        try {
            // 调用SDK发送请求，执行退款
            alipayResponse = client.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            log.info("【支付宝支付】退款失败 error={}", e);
        }
        log.info("[支付退款] response={}", alipayResponse);
    }
}
